import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {ParkingCharge} from "@/types/resp/parkingCharge";
import parkingChargeApi from '@/api/parkingChargeApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import ParkingChargeAdd from "@/pages/parkingCharge/ParkingChargeAdd.tsx";
import ParkingChargeView from "@/pages/parkingCharge/ParkingChargeView.tsx";
import ParkingAreaSelector from "@/pages/parkingArea/ParkingAreaSelector.tsx";
import RoomSelector from "@/pages/room/RoomSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'



const ParkingChargeList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '车位收费信息列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<ParkingCharge[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<ParkingCharge>> = await parkingChargeApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<ParkingCharge> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<ParkingCharge>['columns'] = [
    {title: '车位号', dataIndex: 'parkingAreaNumber', key: 'parkingAreaNumber'},
    {title: '单元房号', dataIndex: 'residentRoomNumber', key: 'residentRoomNumber'},
    {title: '车牌', dataIndex: 'licensePlate', key: 'licensePlate'},
    {title: '使用开始时间', key: 'billingStartDate', render: (_, record) => (
      <div>{record.billingStartDate ? record.billingStartDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '使用结束时间', key: 'billingEndDate', render: (_, record) => (
      <div>{record.billingEndDate ? record.billingEndDate.format('YYYY-MM-DD') : ''}</div>
    )},
    {title: '金额', dataIndex: 'amount', key: 'amount'},
    {title: '备注', dataIndex: 'remark', key: 'remark'},
    {
      title: '操作',
      key: 'action',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [parkingChargeAddVisible, setParkingChargeAddVisible] = useState(false);
  const [parkingChargeViewVisible, setParkingChargeViewVisible] = useState(false);
  const [selectedParkingChargeId, setSelectedParkingChargeId] = useState(0)
  const [selectedParkingCharge, setSelectedParkingCharge] = useState({})

  const onAdd = () => {
    setSelectedParkingChargeId(0)
    setParkingChargeAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedParkingChargeId(id)
    setParkingChargeAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      parkingChargeApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: ParkingCharge) => {
    setSelectedParkingCharge(record)
    setParkingChargeViewVisible(true)
  };

  const [parkingAreaSelectorVisible, setParkingAreaSelectorVisible] = useState(false);
  const findParkingArea = () => {
    setParkingAreaSelectorVisible(true);
  }
  const handleParkingAreaSelected = (selectedParkingArea: { parkingAreaId?: number; parkingAreaNumber?: string; }) => {
    setParkingAreaSelectorVisible(false)
    if (selectedParkingArea && 'parkingAreaId' in selectedParkingArea) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      parkingAreaId: selectedParkingArea['parkingAreaId'],
      parkingAreaNumber: selectedParkingArea['parkingAreaNumber'],
      }));
    }
  };
  const handleCloseParkingAreaSelector = () => {
    setParkingAreaSelectorVisible(false)
  };
  const [roomSelectorVisible, setRoomSelectorVisible] = useState(false);
  const findRoom = () => {
    setRoomSelectorVisible(true);
  }
  const handleRoomSelected = (selectedRoom: { residentRoomId?: number; residentRoomNumber?: string; }) => {
    setRoomSelectorVisible(false)
    if (selectedRoom && 'residentRoomId' in selectedRoom) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      residentRoomId: selectedRoom['residentRoomId'],
      residentRoomNumber: selectedRoom['residentRoomNumber'],
      }));
    }
  };
  const handleCloseRoomSelector = () => {
    setRoomSelectorVisible(false)
  };

  const handleCloseParkingChargeAdd = () => {
    setParkingChargeAddVisible(false)
  };

  const handleCloseParkingChargeView = () => {
    setParkingChargeViewVisible(false)
  };

  const onExport = () => {
    const headers = ['车位号','单元房号','车牌','使用开始时间','使用结束时间','金额','备注']
    parkingChargeApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.parkingAreaNumber,d.residentRoomNumber,d.licensePlate,d.billingStartDate,d.billingEndDate,d.amount,d.remark])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="parkingChargeList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="parkingAreaNumber" label="车位号">
          <Input.Search placeholder="请选择车位号" onSearch={findParkingArea} readOnly={true} />
        </Form.Item>
        <Form.Item name="residentRoomNumber" label="单元房号">
          <Input.Search placeholder="请选择单元房号" onSearch={findRoom} readOnly={true} />
        </Form.Item>
        <Form.Item name="licensePlate" label="车牌">
          <Input maxLength={32} placeholder="请输入车牌"/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<ParkingCharge> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <ParkingAreaSelector visible={parkingAreaSelectorVisible} onParkingAreaSelected={handleParkingAreaSelected} onCloseParkingAreaSelector={handleCloseParkingAreaSelector} />
      <RoomSelector visible={roomSelectorVisible} onRoomSelected={handleRoomSelected} onCloseRoomSelector={handleCloseRoomSelector} />
      <ParkingChargeAdd visible={parkingChargeAddVisible} onCloseParkingChargeAdd={handleCloseParkingChargeAdd} id={selectedParkingChargeId} />
      <ParkingChargeView visible={parkingChargeViewVisible} onCloseParkingChargeView={handleCloseParkingChargeView} viewRow={selectedParkingCharge} />
    </div>
  );
};

export default ParkingChargeList;
